/**
 * [289] 生命游戏
 *
 * @format
 * @lc app=leetcode.cn id=289 lang=javascript
 */

// @lc code=start
/**
 * @param {number[][]} board
 * @return {void} Do not return anything, modify board in-place instead.
 */
// 返回新数组
// var gameOfLife = function (board) {
//     const row = board.length
//     const col = board[0].length
//     const round = [
//         [1, 0],
//         [1, 1],
//         [0, 1],
//         [-1, 1],
//         [-1, 0],
//         [-1, -1],
//         [0, -1],
//         [1, -1]
//     ]
//     const result = []
//     for (let i = 0; i < row; i++) {
//         result.push([])
//         for (let j = 0; j < col; j++) {
//             let count = 0
//             for (let k = 0; k < 8; k++) {
//                 board[i + round[k][1]] &&
//                 (board[i + round[k][1]][j + round[k][0]] === 1 ||
//                     board[i + round[k][1]][j + round[k][0]] === false)
//                     ? count++
//                     : null
//             }
//             if (board[i][j])
//                 count < 2 || count > 3 ? result[i].push(0) : result[i].push(1)
//             else count === 3 ? result[i].push(1) : result[i].push(0)
//         }
//     }
//     return result
// }
// debugger
// console.log(gameOfLife([[0,1,0],[0,0,1],[1,1,1],[0,0,0]]))

// 原地操作
var gameOfLife = function (board) {
    const row = board.length
    const col = board[0].length
    const round = [
        [1, 0],
        [1, 1],
        [0, 1],
        [-1, 1],
        [-1, 0],
        [-1, -1],
        [0, -1],
        [1, -1]
    ]
    for (let i = 0; i < row; i++) {
        for (let j = 0; j < col; j++) {
            let count = 0
            for (let k = 0; k < 8; k++) {
                if (board[i + round[k][0]]) {
                    if (
                        board[i + round[k][0]][j + round[k][1]] === 1 ||
                        board[i + round[k][0]][j + round[k][1]] === false
                    ) {
                        count++
                    }
                }
            }
            if (board[i][j]) {
                count < 2 || count > 3 ? (board[i][j] = false) : null
            } else {
                count === 3 ? (board[i][j] = true) : null
            }
        }
    }
    for (let i = 0; i < row; i++) {
        for (let j = 0; j < col; j++) {
            board[i][j] ? (board[i][j] = 1) : (board[i][j] = 0)
        }
    }
}
// @lc code=end
